package com.manlitech.manlichat.base.exception;


import com.manlitech.manlichat.enums.ResultEnums;
import com.manlitech.manlichat.pojo.Result;
import com.manlitech.manlichat.util.ResultUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

import java.io.PrintWriter;
import java.io.StringWriter;


@ControllerAdvice
@Component
public class ExceptionHandle {
	
	private final static Logger logger = LoggerFactory.getLogger(ExceptionHandle.class);
	
	@ExceptionHandler(value = Exception.class)
    @ResponseBody
    public Result handle(Exception e) {
		logger.error("exceptionmsg="+e.getMessage());
        if (e instanceof MyException) {
        	MyException myException = (MyException) e;
            return ResultUtil.error(myException.getCode(), myException.getMessage());
        }else {
            logger.error("【系统异常】"+e.getStackTrace());
			e.printStackTrace();
            return ResultUtil.error(ResultEnums.UNKONW_ERROR.getCode(),ResultEnums.UNKONW_ERROR.getMsg(),getExceptionToString(e));
        }
    }
	
	public static String getExceptionToString(Throwable e) {
		if (e == null){
			return "";
		}
		StringWriter stringWriter = new StringWriter();
		e.printStackTrace(new PrintWriter(stringWriter));
		return stringWriter.toString();
	}
}
